package a12;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class WordIndex {

	private static Map<String, String> index = new HashMap<String, String>();

	public static void main(String[] args) {
		try {
			FileReader fileReader = new FileReader(
					"//Users//Meg//Downloads//10kwords.txt");
			WordIndex idx = new WordIndex(fileReader);
			System.out
					.println("Enter a word to unscramble, or type end to stop:");
			Scanner sc = new Scanner(System.in);
			String word = sc.nextLine().toLowerCase();
			while (!word.equalsIgnoreCase("end")) {
				if (lookup(word) != null) {
					System.out.println("Your word is: " + index.get(sort(word)));
					System.out.println("\nEnd or try again?");
					word = sc.nextLine().toLowerCase();
				} else {
					System.out
							.println("\nSorry, your vocabulary is too high for me.\nEither that, or your spelling is bad.\nTry again, or type end:");
					word = sc.nextLine().toLowerCase();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Finds words in the index that match a scrambled word.
	 * 
	 * @param scrambled
	 *            word
	 * @return matching words from the index
	 */
	static String lookup(String scrambled) {
		if (index.containsKey(sort(scrambled))) {
			return index.get(sort(scrambled));
		}

		else {
			return null;
		}
	}

	/**
	 * Returns the letters of a String in alphabetized order
	 * 
	 * @param str
	 * @return the alphabetized String
	 */
	private static String sort(String str) {
		byte[] bytes = str.getBytes();
		Arrays.sort(bytes);
		return new String(bytes);
	}

	public WordIndex(InputStreamReader isr) {
		try {
			BufferedReader bufferedReader = new BufferedReader(isr);
			String word = bufferedReader.readLine();
			while (word != null) {
				addToIndex(word);
				word = bufferedReader.readLine();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Adds a word to the index. If the alphabetized word already exists, the
	 * word is appended to a comma-separated list of matching words. For
	 * example:
	 * 
	 * dgo => dog,god
	 * 
	 * @param word
	 */
	private void addToIndex(String word) {
		String temp;
		if (index.containsKey(sort(word))) {
			temp = index.get(sort(word)) + "," + word;
			index.put(sort(word), temp);
		} else {
			index.put(sort(word), word);
		}

	}

}
